package com.ey12.file;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ey12.utils.DateUtil;

/**
 * 
 * @author crystal
 */
public class RefreshStore extends HttpServlet {
	private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
	private static String URL = "";
	private static String USN = "";
	private static String PWD = "";

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */

	private int maxPostSize = 100 * 1024 * 1024;

	public RefreshStore() {
		super();
	}
	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	
	public void destroy() {
		super.destroy();
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		URL = this.getServletContext().getInitParameter("DbUrl");
		USN = this.getServletContext().getInitParameter("DbUsername");
		PWD = this.getServletContext().getInitParameter("DbPwd");
		request.setCharacterEncoding("gbk");
		try{
//		<input type='text' name='data1' size='100' value='QQ���==��������ͨ��==����==��Ϸ��==0.036==510' /><br>
//		<input type='text' name='data2' size='100' value='QQ���==��������ͨ��==�Ծ�==��Ϸ��==0.034==500' /><br>
//		<input type='hidden' name='sh_id' value='2357'>
//		<input type='hidden' name='key' value='d4g5h67j'>
//		<input type='hidden' name='count' value='2'>
		int count =Integer.parseInt(request.getParameter("count"));
		System.out.println(count);
		String sh_id =request.getParameter("sh_id");
		String key =request.getParameter("key");
		List list=new ArrayList();
		for(int i=1;i<=count;i++){
			String item =request.getParameter("data"+i);
			System.out.println(item);
			list.add(item);
		}
		readList(sh_id,list);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage() + "����");
		}
	}



	/**
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo() {
		return "Short description";
	}

	public void readList(String username,List list) {
		try {
//QQ���==��������ͨ��==����==��Ϸ��==0.036==510
			
			int userid=findUserId(username);
			if(userid!=-1){
			List result=new ArrayList();
			for (int i = 0; i < list.size(); i++) {
				String item=list.get(i).toString();	
				System.out.println("item="+item);
				String[] items=item.split("==");
				String gameValue = items[0];				
				String cserverValue = items[1];			
				String servertypeValue =  items[2];
				String campValue =  items[3];
				String moneytypeValue =  items[4];	
				String danweiValue =  items[5];
				String priceValue = items[6];				
				String totalValue = items[7];
				String leastMount = items[8];
				int temp=0;
				if(leastMount!=null){
					temp=Integer.parseInt(leastMount);					
				}	
				int gameid = findGameId(gameValue.trim());
				
				if(gameid!=-1){
					int cserverid = findCserverId(gameid, cserverValue,
						servertypeValue, moneytypeValue, campValue,danweiValue);
					if(cserverid!=-1){
					
					int storeid=findStoreExist(userid,gameid,cserverid);
					if(storeid==-1){
						
					int gameLessBuy = findGameLessBuy(gameValue.trim());
					int least_mount= gameLessBuy;
					
					
					if(temp>gameLessBuy){
						least_mount=temp;
					}
					String sql = "insert into gm_game_store(user_id,game_id,cserver_id,store_num,update_date,price,is_online,least_mount,isDel) ";
						sql = sql + " values(" + userid + "," + gameid + ","
						+ cserverid + "," + totalValue + ",'"
						+ new DateUtil().toTimeString() + "'," + priceValue
						+ ",1,"+least_mount+",1)";
					
						result.add(sql);
					}else{
						String sql = "update gm_game_store set least_mount="+temp+",price="+priceValue+",store_num="+totalValue+",update_date='"+new DateUtil().toTimeString()+"' where user_id="
						+userid+" and game_id="+gameid+" and cserver_id="+cserverid;
						result.add(sql);
					}
				}
				
			 }
			}
			saveGmStore(result);
		}} catch (Exception e) {
			e.printStackTrace();
			System.out.println("������xlRead() : " + e);
		}

	}
	public int findGameLessBuy(String gameName) {
		int id = -1;
		
		String sqlx = "select least_mount from gm_game where game_name='" + gameName
				+ "'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				id = rs.getInt("least_mount");
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return id;
	}
	public String reverse(String item) {
		if ("��".equals(item)) {
			return "2";
		} else {
			return "1";
		}
	}

	public static Connection getConnectionByJDBC() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(URL, USN, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public int findStoreExist(int userid, int gameid, int cserverid) {
		int id = -1;
		
		String sql = "select * from gm_game_store where user_id="
		+userid+" and game_id="+gameid+" and cserver_id="+cserverid;
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				id = rs.getInt("id");
				
			} 
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return id;
	}
	public int findCserverId(int gameId, String cserverName, String severType,
			String unit, String camp,String danwei) {
		int id = -1;
		
		String sqlx = "select g.id from gm_cserver g where g.game_id=" + gameId
				+ " and g.cserver_name='" + cserverName
				+ "' and g.sever_type='" + severType + "' and g.unit='" + unit
				+ "' and g.camp='" + camp + "' and g.danwei='"+danwei+"'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				id = rs.getInt("id");
				
			} else {
				String sql = "insert into gm_cserver(game_id,cserver_name,sever_type,unit,camp,danwei) values("
						+ gameId
						+ ",'"
						+ cserverName
						+ "','"
						+ severType
						+ "','" + unit + "','" + camp + "','"+danwei+"');";
				save(sql);
				System.out.println(sql);
				Statement stmt2 = conn.createStatement();
				ResultSet rs2 = stmt2.executeQuery(sqlx);
				if (rs2.next()) {
					id = rs2.getInt("id");					
				}
				rs2.close();
				stmt2.close();
			
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 
		return id;
	}
	public int findUserId(String username) {
		int id = -1;
		
		String sqlx = "select id from gm_user where user_name='" + username
				+ "'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				id = rs.getInt("id");
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 
		return id;
	}
	public int findGameId(String gameName) {
		int id = -1;
		
		String sqlx = "select id from gm_game where game_name='" + gameName
				+ "'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				id = rs.getInt("id");
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 
		return id;
	}

	public void save(String sql) {
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			stmt.execute(sql);
			stmt.close();
			conn.close();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 
	}

	public void saveGmStore(List list) {
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
		
			for (int i = 0; i < list.size(); i++) {
				System.out.println(list.get(i).toString());
				stmt.execute(list.get(i).toString());				
			}
			stmt.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
	}

	public void test() {
		
		String sqlx = "select t.code,t.name from province t order by t.code asc";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
					ResultSet.CONCUR_READ_ONLY);
			
			ResultSet rs = stmt.executeQuery(sqlx);
			while (rs.next()) {
				String code = rs.getString("code");
				String name = rs.getString("name");
				System.out.println(code + name);
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

}
